import { Injectable, Inject } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, CanActivateChild } from '@angular/router';
import { TokenService, DA_SERVICE_TOKEN } from '@delon/auth';
import { MenuService, Menu } from '@delon/theme';
import { MSProductService, MSProductCategory } from '@brand';
import { UserService } from '@core';
import { of, Observable } from 'rxjs';
import { tap, map } from 'rxjs/operators';

/**
 * 路由守卫服务
 */
@Injectable({ providedIn: 'root' })
export class AuthGuardService implements CanActivate, CanActivateChild {
  constructor(private prod: MSProductService, private router: Router, private userService: UserService) {}

  /**
   * 保护需要登录权限的路由
   * @param state 即将被路由到的url
   */
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const url: string = state.url;
    if (url === '/403' || url === '/404' || url === '/500') {
      return true;
    }

    const ret = this.checkLogin(url);
    if (ret) {
      if (url !== '/home') {
        this.checkMenuAuth(url).subscribe(res => {
          if (!res) {
            this.router.navigate(['/exception/404']);
          }
        });
      }
    }
    return ret;
  }

  /**
   * 保护需要登录权限的子路由
   */
  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.canActivate(route, state);
  }

  checkLogin(url: string): boolean {
    const isLogined = this.userService.isLogin;
    if (isLogined) {
      return true;
    }
    // 未登录, 重定向到登录页
    console.log(`[${url}]当前未登录 重定向到登录页`);
    this.router.navigate(['/account/login']);
    return false;
  }

  checkMenuAuth(url: string): Observable<boolean> {
    return this.prod.getData().pipe(
      map((res: any) => {
        return this.checkMenu(res, url);
      }),
    );
  }

  checkMenu(ms: any[], url: string) {
    for (const menu of ms) {
      if (menu.products && menu.products.length > 0) {
        const ret = this.checkMenu(menu.products, url);
        if (ret) {
          return true;
        }
      } else {
        if (url.startsWith(menu.link)) {
          return true;
        }
      }
    }
    return false;
  }
}
